/*
 * @Autor: lh
 * @Date: 2023-10-13 10:01:49
 * @LastEditors: lh
 * @LastEditTime: 2023-10-13 16:15:51
 * @Description:
 */
import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { type RouteRecordRaw } from "vue-router"
import { constantRoutes, asyncRoutes } from "@/router"
import { flatMultiLevelRoutes } from "@/router/helper"
import routeSettings from "@/config/route"
const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  const routeRoles = route.meta?.roles
  return routeRoles ? roles.some((role) => routeRoles.includes(role)) : true
}
// 侧边栏路由组装
const tabFilassemble = (arr: any, isboo = true) => {
  // let treeMap = [];
  // let findMap = [];
  // for(let i=0,len=arr.length;i<len;i++){
  //   let it = arr[i];
  //   let boor= false;
  //   it.path = it.path ? it.path : "/"
  //   it.meta = {
  //     title: it.name,
  //     svgIcon: it.image || ""
  //     // alwaysShow: true
  //   }
  //   it.component = "" //() => import('@/layouts/index.vue')
  //   if (it.sonMenuList && it.sonMenuList.length > 0) {
  //     if(it.sonMenuList[0].isMenu){
  //       it.children = tabFilassemble(it.sonMenuList,false)
  //     }else{
  //       it.meta['authority'] = tabFilassemble(it.sonMenuList,false)
  //       boor = true;
  //       it.children = []
  //       findMap.push(it)
  //     }
  //   }else{
  //     findMap.push(it)
  //   }
  //   console.log('tabFilassemble',boor)
  //   treeMap.push(it);
  // }
  // if(isboo){
  //   return {
  //     treeMap,
  //     findMap,
  //   }
  // }else{
  //   return treeMap
  // }

  return arr.map((it: any) => {
    let boor = false
    it.path = it.path ? it.path : "/"
    it.meta = {
      title: it.name,
      svgIcon: it.image || ""
      // alwaysShow: true
    }
    it.component = "" //() => import('@/layouts/index.vue')
    if (it.sonMenuList && it.sonMenuList.length > 0) {
      if (it.sonMenuList[0].isMenu) {
        it.children = tabFilassemble(it.sonMenuList)
      } else {
        it.meta["authority"] = tabFilassemble(it.sonMenuList)
        boor = true
      }
    }
    return it
  })
}

/**
 * 把数结构 结构成扁平数组
 * @param {Object} tree 树形数据
 * @return {Array} 返回一个扁平的数组
 */
function findQuestions(tree: any[]) {
  let res = []
  for (let i = 0; i < tree.length; i++) {
    let it = tree[i]
    if (it.sonMenuList.length == 0 || !it.sonMenuList[0].isMenu) {
      res.push(it)
    } else {
      if (it.sonMenuList && it.sonMenuList.length > 0) {
        let newarr = findQuestions(it.sonMenuList)
        if (newarr.length > 0) {
          res = [...res, ...newarr]
        }
      }
    }
  }
  return res
}
const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  // const res: RouteRecordRaw[] = []
  // routes.forEach((route) => {
  //   const tempRoute = { ...route }
  //   if (hasPermission(roles, tempRoute)) {
  //     if (tempRoute.children) {
  //       tempRoute.children = filterAsyncRoutes(tempRoute.children, roles)
  //     }
  //     res.push(tempRoute)
  //   }
  // })
  // return res
  const data: any = JSON.parse(localStorage.getItem("userinfo") || "{}") //await getUserInfoApi()
  let TreeboorObj = tabFilassemble(data.menuList, true)
  // console.log(findQuestions(TreeboorObj),'--TreeboorObj--');

  localStorage.setItem("findMap", JSON.stringify(findQuestions(TreeboorObj)))
  data.menuList = [
    {
      path: "/",
      meta: {
        /**
         * 是否结构
         *  */
        isStructure: true
      },
      component: () => import("@/layouts/index.vue"),
      redirect: "/dashboard",
      children: TreeboorObj
      // children: TreeboorObj.treeMap//tabFilassemble(data.menuList).treeMap
    }
  ]
  return data.menuList
}

export const usePermissionStore = defineStore("permission", () => {
  const routes = ref<RouteRecordRaw[]>([])
  const dynamicRoutes = ref<RouteRecordRaw[]>([])

  const setRoutes = (roles: string[]) => {
    const accessedRoutes = routeSettings.async ? filterAsyncRoutes(asyncRoutes, roles) : asyncRoutes
    console.log(accessedRoutes, "---accessedRoutes---")

    routes.value = constantRoutes.concat(accessedRoutes)
    dynamicRoutes.value = routeSettings.thirdLevelRouteCache ? flatMultiLevelRoutes(accessedRoutes) : accessedRoutes
  }

  return { routes, dynamicRoutes, setRoutes }
})

/** 在 setup 外使用 */
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
